package master

import (
	"bytes"
	"encoding/json"
	"flag"
	"io"
	"net/http"
	"net/url"
)

var server = flag.String("s", "", "服务端")
var host = flag.String("h", "", "主机")
var token = flag.String("t", "", "令牌")

func Url(resource string, query url.Values) string {
	if query == nil {
		query = url.Values{}
	}
	query.Add("host", *host)
	query.Add("token", *token)
	return *server + resource + "?" + query.Encode()
}

func Request[T any, R any](method string, resource string, t *T, query url.Values) (*R, error) {
	var body io.Reader
	if t != nil {
		data, err := json.Marshal(*t)
		if err != nil {
			return nil, err
		}
		body = bytes.NewBuffer(data)
	}
	req, err := http.NewRequest(method, Url(resource, query), body)
	if err != nil {
		return nil, err
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode/100 != 2 {
		var msg string
		if json.Unmarshal(data, &msg) != nil {
			msg = string(data)
		}
		return nil, &Error{status: resp.StatusCode, message: msg}
	}
	if string(data) == "null" {
		return nil, nil
	}
	var r R
	if err = json.Unmarshal(data, &r); err != nil {
		return nil, err
	}
	return &r, nil
}

func GetConfig() (*Config, error) {
	return Request[any, Config]("GET", "/config", nil, nil)
}
